var express = require('express');
var app = express();
var fs = require("fs");
var net = require("net");

var bodyParser = require('body-parser');
var multer  = require('multer');

fs.readFile(('background.jpg'), () =>{});
app.use(express.static('images'));
app.use('/public', express.static('public'));
app.use(bodyParser.urlencoded({ extended: false }));
app.use(multer({ dest: '/tmp/'}).array('image'));
 
app.get('/index.html', function (req, res) {
   res.sendFile( __dirname + "/" + "index.html" );
})

let zhongtong=0;
let yuantong=0;
let shunfeng=0;

app.post('/file_upload', function (req, res) {
  console.log(req.files[0]);  // 上传的文件信息

  var des_file = "images/" + req.files[0].originalname;
  fs.readFile( req.files[0].path, function (err, data) {
    fs.writeFile(des_file, data, function (err) {
      if( err ){
        console.log( err );
      }else{
        var base64Data = data.toString('base64');
        response = {};

        // net.Socket,
        var sock = net.connect({
          port: 5678,
          host: "192.168.43.74",
        }, function() {
          console.log('connected to server!');
        });
        
	      // 连接成功调用的事件
	      sock.on("connect",function() {
		      

          console.log("connect success");
          
          const core = require('@huaweicloud/huaweicloud-sdk-core');
          const ocr = require("@huaweicloud/huaweicloud-sdk-ocr/v1/public-api");

          const ak = process.env.CLOUD_SDK_AK;
          const sk = process.env.CLOUD_SDK_SK;
          const endpoint = "https://ocr.cn-north-4.myhuaweicloud.com";
          const project_id = "d8047c5a9ef04fe3bf7d842c0ab92951";

          const credentials = new core.BasicCredentials()
                    .withAk(ak)
                    .withSk(sk)
                    .withProjectId(project_id)
          const client = ocr.OcrClient.newBuilder()
                        .withCredential(credentials)
                        .withEndpoint(endpoint)
                        .build();
          const request = new ocr.RecognizeGeneralTextRequest();
          const body = new ocr.GeneralTextRequestBody();
          body.withImage(base64Data);
          request.withBody(body);
          const result = client.recognizeGeneralText(request);
          result.then(result => {
            const expressWords = result.result.words_block_list.find(item => item.words.includes('快递')).words;
            response.expressWords=expressWords;
            console.log(response);
            if(expressWords=='中通快递'){
              zhongtong++;
            }
            else if(expressWords=='圆通快递'){
              yuantong++;
            }
            else if(expressWords=='顺丰快递'){
              shunfeng++;
            }
            // Send OCR result back to the web page
            res.json({
              中通快递:zhongtong,
              圆通快递:yuantong,
              顺丰快递:shunfeng
            });
            // 发送数据
            sock.write(expressWords, "utf8");
          }).catch(ex => {
            console.log("exception:", JSON.stringify(ex));
          });
		
        });
        
        // 有错误发生调用的事件
        sock.on("error", function(e) {
          console.log("error", e);
        });
        
        // socket关闭的事件
        sock.on("close", function() {
          console.log("close");
        });
        
        // 对方发送了关闭数据包过来的事件
        sock.on("end", function() {
          console.log("end event");
        });

        // 当有数据发生的时候，调用;
        sock.on("data", function(data) {
          console.log(data);

        });

      }
    });
  });
})

 
var server = app.listen(8081, function () {
  var port = server.address().port
  console.log("应用实例，访问地址为 http://127.0.0.1:%s", port);
})